<template>
  <div class="point-mall-detail">
    <!-- 顶部导航栏 -->
    <van-nav-bar
        title="邻里社区积分商城"
        left-arrow
        @click-left="onClickLeft"
    >

      <template #right>
        <div class="points-info">
          <van-icon name="coin" color="blue" />
          <span class="points-count">我的积分: {{ data.user.points }}</span>
        </div>
      </template>
    </van-nav-bar>

    <!-- 商品图片轮播 -->
    <van-swipe class="product-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item v-for="(image, index) in data.product.images" :key="index">
        <img :src="image" class="product-image" alt="商品图片" />
      </van-swipe-item>
    </van-swipe>

    <!-- 商品基本信息 -->
    <div class="product-info">
      <h1 class="product-title">{{ data.product.name }}</h1>

      <div class="points-section">
        <van-icon name="coin" color="#FF9500" />
        <span class="points-price">{{ data.product.pointsPrice }} 积分</span>
        <van-tag type="success" v-if="data.product.stock > 0">库存充足</van-tag>
        <van-tag type="danger" v-else>已抢完</van-tag>
      </div>

      <p class="product-description">{{ data.product.description }}</p>
    </div>

    <!-- 兑换区域 -->
    <h2 class="exchange-title">
      <i class="fas fa-shopping-cart"></i>
      <span>兑换商品</span>
    </h2>
    <div class="exchange-section">
      <van-cell-group inset>
        <van-cell title="兑换数量" :border="false">
          <template #default>
            <van-stepper
                v-model="data.quantity"
                :min="1"
                :max="data.product.stock"
                @change="onQuantityChange"
            />
          </template>
        </van-cell>

        <van-cell title="总计积分" :border="false">
          <template #default>
            <span class="total-points">{{ data.product.pointsPrice * data.quantity }} 积分</span>
          </template>
        </van-cell>

        <van-cell title="收货地址" border="border" >
          <template #default>
            <span v-if="addresses">{{ addresses }}</span>
            <span v-else style="color: #ccc">请前往个人中心完善地址信息</span>
          </template>
        </van-cell>
<!--        <div>-->
<!--          <label for="address">收货地址：</label>-->
<!--          <textarea class="address-input" id="address" placeholder="请输入详细的收货地址"></textarea>-->
<!--        </div>-->
      </van-cell-group>

      <div class="exchange-button-container">
        <van-button
            type="primary"
            block
            round
            @click="confirmExchange"
        >
          确认兑换
        </van-button>
      </div>
    </div>

    <!-- 兑换成功弹窗 -->
    <van-dialog
        v-model:show="data.showSuccessDialog"
        title="兑换成功"
        show-cancel-button
        @confirm="gotoOrderList"
    >
      <div class="success-message">
        <van-icon name="success" color="#07C160" size="48" />
        <p>您已成功兑换商品，我们将尽快为您发货~</p>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, computed,  onMounted, reactive } from 'vue'
import {useRoute, useRouter} from 'vue-router'
import axios from "@/utils/axios.ts";

// 路由相关
const router = useRouter()
const route = useRoute();
const data = reactive({
  product: {
    productId: 0,
    typeId: 0,
    name: '',
    description: '',
    images: [],
    pointsPrice: 0,
    stock: 0,
    status: 0,
    created_at: '',
    updated_at: ''
  },
  user: {
    userId: 0,
    phone: '',
    originalpwd: '',
    password: '',
    salt: '',
    repwdTimes: 0,
    nickname: '',
    avatar: '',
    building: '',
    unit: '',
    room: '',
    points: 0,
    createdAt: '',
    updatedAt: '',
    status: 0
  },
  order: {
    userId: 0,
    productId: 0,
    quantity :0,
    pointsAmount:0,
    shippingInfo: '',
  },
  showSuccessDialog: false,
  quantity:1,

})
const productId = route.query.pid;
// const userId = route.query.uid;
onMounted( () => {
  console.log("route: ", route.query);
  console.log("商品id: ", productId);
  axios.get(`/api/mall/products/${productId}`)
      .then(res => {
        if (res.code == 200){
          console.log("商品数据: ", res.data);
          data.product = res.data;
          console.log("图片: ", JSON.parse(res.data.images));
          data.product.images = JSON.parse(res.data.images)
        }
      })
  axios.post("/api/users/getUserInfo")
      .then(res => {
        if (res.code == 200){
          console.log("响应的用户数据: ", res.data);
          data.user = res.data;
        }else {
          console.log("用户数据获取失败");
        }
      })
})


//
// // 地址相关
const addresses = computed(() => {
  console.log(data.user.unit.trim())
  if (data.user.building.trim() == "" || data.user.unit.trim() == "" || data.user.room.trim() == "") {
    return null;
  }else {
    return `${data.user.building}栋 ${data.user.unit}单元 ${data.user.room}号`;
  }
});



// 返回按钮点击
const onClickLeft = () => {
  router.back()
}
//
// 确认兑换
const confirmExchange = () => {
  console.log("addresses: ",addresses.value);
  if (addresses.value === null || addresses.value == '') {
    ElMessage({
      message: "地址信息不完全, 请前往个人中心设置地址",
      duration: 2000,
      type: 'warning'
    })
    console.log("3333")
    router.push({name: "profile", query: {uid: data.user.userId}})

    return;
  }
  if (data.product.pointsPrice * data.quantity > data.user.points) {
    ElMessage({
      message: "您的积分不足",
      duration: 2000,
      type: 'warning'
    })
    return
  }
  if (data.product.stock <= 0) {
    ElMessage({
      message: "商品已抢完",
      duration: 2000,
      type: 'warning'
    })
    return
  }
  data.order.userId = data.user.userId;
  data.order.productId = data.product.productId;
  data.order.quantity  = data.quantity;
  data.order.pointsAmount = data.product.pointsPrice * data.quantity;
  data.order.shippingInfo = `${data.user.nickname}${data.user.phone}${addresses}`;
  axios.post("/api/mallOrders/addOrder", data.order)
      .then(res => {
        console.log("订单响应数据: ", res)
        if (res.code == 200) {
          console.log("订单生成成功");
          ElMessage({
            message: "订单生成成功",
            duration: 2000,
            type: 'primary'
          })
        }
      })
}



</script>

<style scoped>
.point-mall-detail {
  background-color: #f7f8fa;
  min-height: 100vh;
}

/* 导航栏样式 */
.points-info {
  display: flex;
  align-items: center;
  color: #fff;
  font-size: 14px;
  padding-right: 10px;
}

.points-count {
  margin-left: 4px;
}

/* 商品轮播样式 */
.product-swipe {
  height: 300px;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 商品信息样式 */
.product-info {
  padding: 16px;
  background-color: #fff;
  margin-bottom: 10px;
}

.product-title {
  font-size: 18px;
  font-weight: 500;
  margin: 0 0 12px 0;
  color: #333;
  line-height: 1.4;
}

.points-section {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.points-price {
  font-size: 20px;
  color: #FF9500;
  font-weight: bold;
  margin-left: 6px;
  margin-right: 10px;
}

.product-description {
  font-size: 14px;
  color: #666;
  margin: 0;
  line-height: 1.5;
}

/* 兑换区域样式 */
.exchange-section {
  padding: 16px;
  background-color: #fff;
  margin-bottom: 10px;
}

.total-points {
  color: #FF9500;
  font-weight: bold;
}

.address-text {
  color: #666;
}

.exchange-button-container {
  margin-top: 20px;
  padding: 0 16px;
}

/* 商品详情样式 */
.detail-section {
  padding: 16px;
  background-color: #fff;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 16px 0;
  color: #333;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.detail-content {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.detail-images {
  width: 100%;
  margin-bottom: 16px;
}

.detail-images img {
  width: 100%;
  margin-bottom: 8px;
  border-radius: 4px;
}

/* 地址弹窗样式 */
.address-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.popup-title {
  padding: 16px;
  font-size: 16px;
  font-weight: 500;
  border-bottom: 1px solid #eee;
}

.address-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.address-item {
  width: 100%;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.address-info {
  margin-left: 24px;
}

.address-name-phone {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.address-name {
  font-weight: 500;
}

.address-phone {
  color: #666;
  font-size: 14px;
}

.address-detail {
  color: #666;
  font-size: 14px;
  line-height: 1.4;
}

.add-address-btn {
  padding: 16px;
  border-top: 1px solid #eee;
}

/* 成功弹窗样式 */
.success-message {
  text-align: center;
  padding: 20px 0;
}

.success-message p {
  margin-top: 16px;
  color: #333;
}
</style>
